﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-spin :spinning="loading">
      <a-card class="mainInfo"><a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">

        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据日期" prop="dDate">
              <a-date-picker v-model="entity.dDate" autocomplete="off" placeholder="单据日期" style="width: 100%;" valueFormat="YYYY-MM-DD" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="销售订单号" prop="cSOCode">
              <a-input v-model="entity.cSOCode" autocomplete="off" placeholder="自动生成或手填销售订单号" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="销售类型" prop="cSTCode" :disabled="disabled">
              <dictionariesTemplate v-model="entity.cSTCode" keyword="SalesPattern" :list="SalesPatternList" @rowchange="cSTCodeChange"></dictionariesTemplate>

            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <!-- v-model="entity.cCusCode" disabled -->
            <a-form-model-item label="客户" prop="cCusCode">
              <a-row>
                <a-col :span="20">
                  <a-input :value="entity.cCusCode?(entity.cCusCode+'/'+entity.cCusName):''" disabled></a-input>
                </a-col>
                <a-col :span="4"><a-button icon="search" type="primary" style="width: 100%;margin-top: 4px;" @click="openClient"></a-button></a-col>
              </a-row>

            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户订单号" prop="cDefine2">
              <a-input v-model="entity.cDefine2" autocomplete="off" placeholder="客户订单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="业务员" prop="cPersonCode">
              <a-input v-model="entity.cPersonCode" autocomplete="off" placeholder="业务员" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="预交日" prop="dPreDateBT">
              <a-date-picker
                v-model="entity.dPreDateBT"
                autocomplete="off"
                placeholder="单据日期"
                :disabled-date="disabledDate"
                style="width: 100%;"
                valueFormat="YYYY-MM-DD"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="税率(%)" prop="iTaxRate">
              <dictionariesTemplate v-model="entity.iTaxRate" keyword="TaxRate" :list="TaxRateList"></dictionariesTemplate>
            <!-- <a-input v-model="entity.iTaxRate" autocomplete="off" placeholder="税率" default-value="13.00"/> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="币种" prop="cexch_name">
              <dictionariesTemplate v-model="entity.cexch_name" keyword="Currency" :list="CurrencyList"></dictionariesTemplate>

            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="汇率" prop="iExchRate">
              <a-input-number v-model="entity.iExchRate" autocomplete="off" placeholder="汇率" style="width: 100%;" :min="0"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="付款条款" prop="cDefine11">
              <dictionariesTemplateSerach v-model="entity.cDefine11" keyword="PaymentTerms"></dictionariesTemplateSerach>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="支付方式" prop="cDefine9">
              <dictionariesTemplate v-model="entity.cDefine9" keyword="PaymentMethod" :list="PaymentMethodList"></dictionariesTemplate>

            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="发货方式" prop="cDefine10">
              <dictionariesTemplate v-model="entity.cDefine10" keyword="DeliveryMethod" :list="DeliveryMethodList"></dictionariesTemplate>
            <!-- <a-select v-model="entity.cDefine10" allowClear placeholder="交付方式">
                <a-select-option v-for="item in DeliveryMethodData" :key="item.DicName" :value="item.DicName">
                  {{ item.DicName }}
                </a-select-option>
              </a-select> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="签署地" prop="cDefine12">
              <a-input v-model="entity.cDefine12" autocomplete="off" placeholder="签署地" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="6">
            <a-form-model-item label="收货地址" prop="cCusOAddress">
              <a-input v-model="entity.cCusOAddress" autocomplete="off" placeholder="收货地址" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="收货人" prop="ccontactname">
              <a-input v-model="entity.ccontactname" autocomplete="off" placeholder="收货人" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="收货人电话" prop="cmobilephone">
              <a-input v-model="entity.cmobilephone" autocomplete="off" placeholder="收货人电话" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="备注" prop="cMemo">
              <a-input v-model="entity.cMemo" autocomplete="off" placeholder="备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model> </a-card>
      <div class="detailInfo" >
        <div class="itemButton" style="margin-bottom: 10px;margin-top: 10px;">
          <a-button :loading="loading" :disabled="disabled" icon="plus" type="primary" @click="addTable"> 添加</a-button>&nbsp;
          <a-button
            v-if="hasPerm('Base_DictionaryDetails.Delete')"
            :disabled="!hasSelected()"
            :loading="loading"
            icon="minus"
            type="primary"
            @click="handleDelete('', selectedRowKeys, selectedRows)"
          >
            删除 </a-button
          >&nbsp;
          <a-button
            :disabled="this.DetaiData.length === 0"
            :loading="loading"
            icon="delete"
            type="danger"
            @click="clearAll"
          >
            全部清空</a-button
          >
        </div>
        <a-table
          id="detailsTable"
          ref="table"
          :bordered="true"
          :columns="columns"
          :dataSource="DetaiDataComputed"
          :loading="tableLoading"
          :pagination="false"
          :rowKey="(row, index) => row.I_id || row.Id"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
          :scroll="{ x: 1600, y: tableHight }"
          size="small"
          @change="handleTableChange"

        >
          <!-- 数量 -->
          <template slot="iQuantity" slot-scope="text, record, index">
            <a-input-number style="width:100%" v-model="record.iQuantity" @change="tableChange($event,'iQuantity',index)" ></a-input-number>
          </template>
          <!-- 底价 -->
<!--          <template slot="BasePrice" slot-scope="text, record, index">-->
<!--            <a-input-number style="width:100%" v-model="record.BasePrice" @change="tableChange($event,'BasePrice',index)" :min="0"></a-input-number>-->
<!--          </template>-->
          <!-- 含税单价 -->
<!--          <template slot="iTaxUnitPrice" slot-scope="text, record, index">-->
<!--            <a-input-number style="width:100%" v-model="record.iTaxUnitPrice" @change="tableChange($event,'iTaxUnitPrice',index)" :min="0"></a-input-number>-->
<!--          </template>-->
          <!-- 数量 -->
          <template slot="iTaxRate" slot-scope="text, record, index">
            <a-input-number style="width:100%" v-model="record.iTaxRate" @change="tableChange($event,'iTaxRate',index)" ></a-input-number>
          </template>
          <template slot="action" slot-scope="text, record, index">
            <a
              v-if="hasPerm('Base_DictionaryDetails.Delete')"
              :disabled="disabled"
              @click.stop="handleDelete(index, [record.I_id], [record])"
            >删除</a
            >
          </template>
        </a-table>
      </div>
    </a-spin>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '4px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button @click="close">取消</a-button>&nbsp;
      <a-button :loading="loading" type="primary" :disabled="disabled" @click="handleSubmit"> 保存</a-button>
    </div>

    <materialChoose ref="materialChoose" :deptId="deptId" @onChoose="onChoose"></materialChoose>
    <clientChoose ref="clientChoose" :deptId="deptId" @onChoose="cCusCodeChange"></clientChoose>
  </a-drawer>
</template>

<script>
import moment from 'moment'
import materialChoose from './materialChoose'
import clientChoose from './clientChoose'
import dictionariesTemplate from '@/components/Dictionaries/dictionariesTemplate.vue'
import dictionariesTemplateSerach from '@/components/Dictionaries/dictionariesTemplateSerach.vue'

function formatNumber (value) {
  return Number(value).toFixed(2)
  // const roundedNum = Math.round(value * 100) / 100
  // return roundedNum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
export default {
  components: {
    materialChoose, dictionariesTemplate, dictionariesTemplateSerach, clientChoose
  },
  props: {
    parentObj: {
      type: Object,
      default () {
        return {}
      }
    },
    deptId: { default: '', type: String } // 组织ID
  },
  data () {
    return {
      tableLoading: false,
      tableHight: 570, // 表格高度
      selectedRows: [],
      disabled: true,
      selectedRowKeys: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: {
        field: 'Id',
        order: 'desc'
      },
      columns: [
        { title: '存货编码', dataIndex: 'cInvCode', align: 'center', width: '10%' },
        { title: '存货名称', dataIndex: 'cInvName', align: 'center', width: '10%' },
        { title: '规格型号', dataIndex: 'cInvStd', width: '10%', align: 'center' },
        { title: '单位', dataIndex: 'cComUnitName', width: '4%', align: 'center', scopedSlots: { customRender: 'cComUnitName' } },
        // { title: '产地', dataIndex: 'cDefine23', width: '10%', align: 'center' },
        { title: '等级', dataIndex: 'cDefine22', width: '10%', align: 'center', scopedSlots: { customRender: 'cDefine22' } },
        // { title: '换算率', dataIndex: 'iInvExchRate', width: '10%', align: 'center', scopedSlots: { customRender: 'iInvExchRate' } },
        { title: '数量', dataIndex: 'iQuantity', width: '8%', align: 'center', scopedSlots: { customRender: 'iQuantity' } },
        { title: '底价', dataIndex: 'BasePrice', width: '10%', align: 'center', scopedSlots: { customRender: 'BasePrice' } },
        { title: '含税单价', dataIndex: 'iTaxUnitPrice', width: '10%', align: 'center', scopedSlots: { customRender: 'iTaxUnitPrice' } },
        { title: '价税合计', dataIndex: 'iSum', width: '10%', align: 'right', scopedSlots: { customRender: 'iSum' } },
        // { title: '无税单价', dataIndex: 'iUnitPrice', width: '10%', align: 'right', scopedSlots: { customRender: 'iUnitPrice' } },
        { title: '无税金额', dataIndex: 'iMoney', width: '10%', align: 'right', scopedSlots: { customRender: 'iMoney' } },
        { title: '税额', dataIndex: 'iTax', width: '10%', align: 'right', scopedSlots: { customRender: 'iTax' } },
        // 报价 字段待确定
        // { title: '报价', dataIndex: 'cSAComUnit', width: '10%', align: 'center', scopedSlots: { customRender: 'cSAComUnit' } },
        { title: '税率(%)', dataIndex: 'iTaxRate', width: '10%', align: 'right', scopedSlots: { customRender: 'iTaxRate' } },
        // { title: '折扣额', dataIndex: 'iDisCount', width: '10%', align: 'center', scopedSlots: { customRender: 'iDisCount' } },
        // { title: '扣率(%)', dataIndex: 'KL', width: '10%', align: 'center', scopedSlots: { customRender: 'KL' } },
        // { title: '扣率2(%)', dataIndex: 'KL2', width: '10%', align: 'center', scopedSlots: { customRender: 'KL2' } },
        // { title: '本币单价', dataIndex: 'iNatUnitPrice', width: '10%', align: 'right', scopedSlots: { customRender: 'iNatUnitPrice' } },
        // { title: '本币金额', dataIndex: 'iNatMoney', width: '10%', align: 'right', scopedSlots: { customRender: 'iNatMoney' } },
        // { title: '本币税额', dataIndex: 'iNatTax', width: '10%', align: 'right', scopedSlots: { customRender: 'iNatMoney' } },
        // { title: '本币价税合计', dataIndex: 'iNatSum', width: '10%', align: 'right', scopedSlots: { customRender: 'iNatSum' } },
        { title: '操作', dataIndex: 'action', align: 'left', width: '60px', fixed: 'right', scopedSlots: { customRender: 'action' } }
      ],
      DetaiData: [],
      SystemTypeData: [],
      MaterialClassificationData: [],
      MaterialPropertiesData: [],
      PaymentMethodData: [],
      DeliveryMethodData: [],
      CompanyIdTreeData: [],
      CustomerData: [],
      DepartmentIdTreeData: [],
      UnitData: [],
      UserInfo: {},
      PaymentTermsData: [],
      AccompanyingDocumentsData: [],
      ShippingConditionsData: [],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: {},
      rules: {
        dDate: [
          { required: true, message: '请选择单据日期', trigger: 'change' }
        ],
        cSTCode: [
          { required: true, message: '请选择销售类型', trigger: 'change' }
        ],
        iTaxRate: [
          { required: true, message: '请选择税率', trigger: 'change' }
        ],
        cexch_name: [
          { required: true, message: '请选择币种', trigger: 'change' }
        ],
        iExchRate: [
          { required: true, message: '请输入汇率', trigger: 'blur' }
        ],
        cDefine9: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        cDefine10: [
          { required: true, message: '请选择发货方式', trigger: 'change' }
        ],
        cCusCode: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ]

      },
      title: '',
      TaxRateList: [], // 税率列表
      CurrencyList: [], // 币种列表
      PaymentMethodList: [], // 付款方式
      DeliveryMethodList: [], // 交付方式
      SalesPatternList: [], // 销售类型
      ConditionsList: []// 返料规则列表
    }
  },
  computed: {
    DetaiDataComputed () {
      return this.DetaiData.map(item => {
        // // 价税合计 数量*含税单价
        this.$set(item, 'iSum', formatNumber(this.$number.mut(Number(item.iQuantity) || 0, Number(item.iTaxUnitPrice) || 0)))
        // 无税单价 含税单价/1+税率
        this.$set(item, 'iUnitPrice', formatNumber(this.$number.dev(Number(item.iTaxUnitPrice) || 0, this.$number.add(1, Number(item.iTaxRate) / 100))))
        // 无价税额 数量*无税单价 含税金额/1+税率
        this.$set(item, 'iMoney', formatNumber(this.$number.dev(Number(item.iSum) || 0, this.$number.add(1, Number(item.iTaxRate) / 100))))
        // 税额 价税合计-无价税额
        this.$set(item, 'iTax', formatNumber(this.$number.minus(Number(item.iSum) || 0, Number(item.iMoney) || 0)))
        // 件数 数量/换算率
        this.$set(item, 'iNum', formatNumber(this.$number.dev(Number(item.iQuantity) || 0, Number(item.iInvExchRate) || 0)))

        // // 折扣额 合计*（1-扣率）=折扣额
        this.$set(item, 'iDisCount', (this.$number.mut(Number(item.iSum), this.$number.minus(1, this.$number.dev(Number(item.KL), 100)))))
        // // 扣率 1-折扣额/合计=扣率
        this.$set(item, 'KL', this.$number.mut(100, (this.$number.minus(1, this.$number.dev(Number(item.iDisCount), Number(item.iSum))))))
        // 本币单价 无税单价*主表汇率
        this.$set(item, 'iNatUnitPrice', formatNumber(this.$number.mut(Number(item.iUnitPrice), Number(this.entity.iExchRate))))
        // 本币金额 无税金额*主表汇率
        this.$set(item, 'iNatMoney', formatNumber(this.$number.mut(Number(item.iMoney), Number(this.entity.iExchRate))))
        // 本币价税合计 价税合计*主表汇率
        this.$set(item, 'iNatSum', formatNumber(this.$number.mut(Number(item.iSum), Number(this.entity.iExchRate))))
        // 本币税额 税额*主表汇率
        this.$set(item, 'iNatTax', formatNumber(this.$number.mut(Number(item.iTax), Number(this.entity.iExchRate))))
        return {
          ...item

        }
      })
    }
  },
  methods: {
    cSTCodeChange (obj) {
      this.$set(this.entity, 'cSTCode', obj.DicValue)
      this.$set(this.entity, 'cSTName', obj.DicName)
      console.log(this.entity)
    },
    openClient () {
      this.$refs.clientChoose.openChoose(this.entity.CompanyId)
    },
    disabledDate (current) {
      // Can not select days before today and today
      return current && current < moment(this.entity.dDate || '')
    },
    getDepartName () {
      console.log(this.entity.cDepCode)
      console.log(this.DepartmentIdTreeData)
      const obj = this.DepartmentIdTreeData.find(item => {
        return item.DeptCode === this.entity.cDepCode
      })
      this.$set(this.entity, 'DepartName', obj.Name)
      console.log(this.entity.DepartName)
    },
    // 获取返料规则列表
    getDataListByConditions () {
      this.$http.post('/GiftManagement/GMM_GiftMaterialRuleMain/GetDataListByConditions', {
        'PageIndex': 1,
        'PageRows': 999999,
        'SortField': 'StartDate',
        'SortType': 'desc'
      }).then(res => {
        if (res.Success) {
          this.ConditionsList = res.Data
        } else {
          this.ConditionsList = []
        }
      })
    },
    // 获取字典列表并默认值
    getInitialData () {
      const arr = ['TaxRate', 'Currency', 'PaymentMethod', 'DeliveryMethod', 'SalesPattern']
      arr.forEach(item => {
        this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          'Condition': 'DicKey',
          'Keyword': item
        }).then(res => {
          if (res.Success) {
            this[item + 'List'] = res.Data.DictionaryDetailsList || []
            if (res.Data.DictionaryDetailsList.length > 0) {
              if (this.title === '新建销售订单主表信息') {
                if (item === 'TaxRate') {
                  this.$set(this.entity, 'iTaxRate', res.Data.DictionaryDetailsList[res.Data.DictionaryDetailsList.length - 1].DicName)
                  return
                }
                if (item === 'Currency') {
                  this.$set(this.entity, 'cexch_name', res.Data.DictionaryDetailsList[res.Data.DictionaryDetailsList.length - 1].DicName)
                  return
                }
                if (item === 'PaymentMethod') {
                  this.$set(this.entity, 'cDefine9', res.Data.DictionaryDetailsList[res.Data.DictionaryDetailsList.length - 1].DicName)
                  return
                }
                if (item === 'DeliveryMethod') {
                  this.$set(this.entity, 'cDefine10', res.Data.DictionaryDetailsList[res.Data.DictionaryDetailsList.length - 1].DicName)
                  return
                }
                if (item === 'SalesPattern') {
                  this.$set(this.entity, 'cSTCode', res.Data.DictionaryDetailsList[0].DicValue)
                  this.$set(this.entity, 'cSTName', res.Data.DictionaryDetailsList[0].DicName)
                }
              }
            }
          }
        })
      })
    },

    // 客户选择
    cCusCodeChange (arr) {
      const obj = arr[0]

      // const obj = this.CustomerData.find(item => {
      //   return item.cCusCode === a
      // })
      if (obj) {
        this.$set(this.entity, 'cCusCode', obj.cCusCode)
        this.$set(this.entity, 'cCusName', obj.cCusName)
        this.$set(this.entity, 'ReceivingUnit', obj.ReceivingUnit)
        this.$set(this.entity, 'ccontactname', obj.Addressee)
        this.$set(this.entity, 'cmobilephone', obj.TelNumber)
        this.$set(this.entity, 'cCusOAddress', obj.Address)
        this.$set(this.entity, 'cPersonCode', obj.PrincipalName)
        this.$refs.form.validateField('cCusCode')
      }
    },
    loadRow (record, index) {
      return {
        on: {
          click: () => {
            if (record.disabled) return
            const key = record.I_id
            if (this.selectedRowKeys.includes(key)) {
              const index = this.selectedRowKeys.findIndex(skey => skey === key)
              this.selectedRowKeys.splice(index, 1)
              this.selectedRows.splice(index, 1)
            } else {
              this.selectedRowKeys.push(key)
              this.selectedRows.push(record)
            }
          }
        }
      }
    },
    tableChange (val, key, index, row) {
      console.log(val)
      var obj = this.DetaiData[index]
      this.$set(this.DetaiData[index], key, val)
      if (key === 'iDisCount') {
        // 扣率 1-折扣额/合计=扣率
        this.$set(this.DetaiData[index], 'KL', this.$number.mut(100, (this.$number.minus(1, this.$number.dev(Number(obj.iDisCount), Number(obj.iSum))))))
      } else if (key === 'KL') {
      // 折扣额 合计*（1-扣率）=折扣额
        this.$set(this.DetaiData[index], 'iDisCount', (this.$number.mut(Number(obj.iSum), this.$number.minus(1, this.$number.dev(Number(obj.KL), 100)))))
      }
    },
    onChoose (arr) {
      this.tableLoading = true
      const nArr = [...arr]
      nArr.forEach(item => {
        this.$set(item, 'cInvCode', item.Code)
        this.$set(item, 'cInvName', item.Name)
        this.$set(item, 'cInvStd', item.Spec)
        this.$set(item, 'cComUnitName', item.SaleName)
        this.$set(item, 'cDefine23', item.Producer)
        this.$set(item, 'cDefine22', item.LevelName)
        this.$set(item, 'InvId', item.Id)
        this.$set(item, 'iTaxRate', this.entity.iTaxRate)
        delete item.Id
      })
      console.log(nArr)
      if (this.DetaiData.length > 0) {
        var newarr = []
        var repetitionArr = []
        nArr.forEach(item => {
          var index = this.DetaiData.findIndex(val => {
            return val.InvId === item.InvId
          })
          if (index !== -1) {
            repetitionArr.push(item)
          } else {
            newarr.push(item)
          }
        })
        this.DetaiData = [ ...newarr, ...this.DetaiData ]
        repetitionArr.forEach(item => {
          this.$message.warning(item.cInvName + '已存在')
        })
      } else {
        this.DetaiData = [...nArr, ...this.DetaiData]
      }

      this.tableLoading = false
    },
    async init () {
      this.visible = true
      this.entity = {}
      this.DetaiData = []
      this.$set(this.entity, 'dDate', moment().format('YYYY-MM-DD'))
      this.getCompanyList()
      // 获取字典列表与默认值
      this.getInitialData()
      // 返料规则列表
      this.getDataListByConditions()
      this.$set(this.entity, 'iExchRate', 1)
      if (this.title === '新建销售订单主表信息') {
        if (localStorage.getItem('UserInfo')) {
          this.UserInfo = JSON.parse(localStorage.getItem('UserInfo'))
          // 默认 公司 部门 业务员
          this.$set(this.entity, 'cPersonCode', this.UserInfo.StaffName)
          this.$set(this.entity, 'CompanyId', this.UserInfo.CompanyId)
          await this.getDepartmentList(this.UserInfo.CompanyId)
          const obj = this.DepartmentIdTreeData.find(item => {
            return this.UserInfo.DepartId === item.Id
          })
          if (obj) {
            this.$set(this.entity, 'cDepCode', obj.DeptCode)
          } else {
            this.$set(this.entity, 'cDepCode', undefined)
          }
        }
      }

      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
        this.tableHight = this.getTableHeight(true) - 145
      })
    },
    async openForm (id, title, flag) {
      this.title = title
      this.loading = true
      this.disabled = flag
      await this.init()
      this.loading = false

      if (id) {
        this.loading = true
        this.$http.post('/OrderManagement/SO_SOMain/GetTheData', { id: id }).then(resJson => {
          this.loading = false
          this.entity = resJson.Data || {}
          this.DetaiData = resJson.Data.SODetails || []
        })
      }
    },
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        if (!this.DetaiData.length) {
          return this.$message.error('请添加物料后保存！')
        }
        this.loading = true
        const arr = []
        this.DetaiData.forEach(item => {
          if ((item.iTaxRate === null || item.iTaxRate === undefined || item.iTaxRate === '') ||
          (item.iQuantity === null || item.iQuantity === undefined || item.iQuantity === '') ||
            (item.BasePrice === null || item.BasePrice === undefined || item.BasePrice === '') ||
          (item.iTaxUnitPrice === null || item.iTaxUnitPrice === undefined || item.iTaxUnitPrice === '')) {
            arr.push(item)
          }
        })
        if (arr.length > 0) {
          this.loading = false
          var str = ''
          arr.forEach(item => {
            str = str + `存货名称：${item.cInvName},存货编码：${item.cInvCode},未填写完整,`
          })
          str = str + '请检查！'
          this.$warning({
            title: '提示',
            content: str
          })
          return
        }
        this.loading = true
        const data = {
          ...this.entity,
          SODetails: [...this.DetaiData]
        }
        if (this.title.includes('变更')) {
          this.$http.post('/OrderManagement/SO_SOMain/ChangeData', data).then(resJson => {
            this.loading = false
            if (resJson.Success) {
              this.$message.success('操作成功!')
              this.loading = false
              this.visible = false
              this.$emit('returnMain')
            } else {
              this.$message.error(resJson.Msg)
              this.loading = false
            }
          })
        } else {
          this.$http.post('/OrderManagement/SO_SOMain/SaveData', data).then(resJson => {
            this.loading = false
            if (resJson.Success) {
              this.$message.success('操作成功!')
              this.loading = false
              this.visible = false
              this.$emit('returnMain')
            } else {
              this.$message.error(resJson.Msg)
              this.loading = false
            }
          })
        }
      })
    },
    close () {
      this.visible = false
      for (let index = 1; index < 5; index++) {
        this['data' + index] = []
      }
      this.entity = {}
    },
    // 非空校验
    validEmpty (index, name, tips) {
      return (rule, value, callback) => {
        const data = this.DetaiData[index][name]
        if (!data) {
          this.$message.warning('列表第' + (index + 1) + '行：' + tips)
          callback(tips || '必填')
        } else {
          callback()
        }
      }
    },
    // 子表删除
    handleDelete (index, ids, rows) {
      let deleteIdArr = []
      // 给每一行设置选中值用于后续判断逻辑
      rows.forEach((item) => (item['checked'] = true))
      // this.DetaiData.forEach((item) => (item['checked'] = true))
      // 过滤有id的列表用于提交请求id数组
      const newDetaiData = rows.filter((item) => item.Id)
      if (newDetaiData.length > 0) {
        // 说明有id
        deleteIdArr = newDetaiData.map((item) => {
          return item.Id
        })
      }

      // if (this.title === '编辑销售订单主表信息') {
      //   // 判断如果是当前行删除  直接删除
      //   if (ids === undefined) return this.DetaiData.splice(index, 1)
      //   // 判断要删除的数组中是否存在返回的id列表 再弹窗 否则直接删除即可
      //   const isBool = rows.some((item) => item.Id)
      //   if (isBool) {
      //     this.$confirm('确认删除吗?', '提示', {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning'
      //     }).then(() => {
      //       return new Promise((resolve, reject) => {
      //         this.$http.post('/OrderManagement/SO_SODetails/DeleteData', deleteIdArr).then((res) => {
      //           if (res.Success) {
      //             this.loading = false
      //             // 对比处理id  过滤出没有符合条件的重新赋值子表
      //             this.DetaiData.forEach(item => {
      //               deleteIdArr.forEach(v => {
      //                 if (item.Id === v) {
      //                   item.checked = true
      //                 }
      //               })
      //             })
      //             // 过滤出没有选中删除的数组重新赋值 为已删除列表
      //             const resultArr = this.DetaiData.filter((item) => !item.checked)
      //             this.DetaiData = resultArr
      //             // 删除选中列表初始化
      //             this.selectedRowKeys = []
      //             this.$message.success('删除成功')
      //           } else {
      //             this.loading = false
      //             // 删除选中列表初始化
      //             this.selectedRowKeys = []
      //             this.$message.error(res.Msg)
      //           }
      //         })
      //       }).catch(() => console.log('Oops errors!'))
      //     })
      //   } else {
      //     const resultArr = this.DetaiData.filter((item) => !item.checked)
      //     this.DetaiData = resultArr
      //     // 删除选中列表初始化
      //     this.selectedRowKeys = []
      //   }
      // } else {
        // 给每一行设置选中值用于后续判断逻辑
        this.DetaiData.forEach((item) => (item['checked'] = true))
        // 过滤出没有选中删除的数组重新赋值 为已删除列表
        const resultArr = this.DetaiData.filter(item => item.Id !== rows[0].Id)
        this.DetaiData = resultArr
        // 删除选中列表初始化
        this.selectedRowKeys = []
      // }
    },
    // 添加一行记录
    addTable () {
      if (!this.entity.cCusCode) {
        alert('请先选择客户！')
        return
      }
      this.$refs.materialChoose.openChoose(this.entity.cCusCode)
    },
    // 清空所有子表数据
    clearAll () {
      const that = this
      const isBool = this.DetaiData.some((item) => item.Id)
      const IdArr = this.DetaiData.map((item) => item.Id)
      //  判断全部清空时是否存在id的子列表。如果存在走确认删除逻辑 否则正常删除即可
      if (isBool && this.title === '编辑销售订单主表信息') {
        this.$confirm({
          title: '是否清空全部子项记录信息?',
          onOk: () => {
            this.loading = true

            that.$http.post('/OrderManagement/SO_SODetails/DeleteData', IdArr).then((res) => {
              if (res.Success) {
                that.DetaiData = []
                that.$message.success('已清空')
                that.loading = false
              } else {
                that.$message.error(res.Msg)
                that.loading = false
              }
            })
          },
          onCancel: () => {
            that.loading = false
          }
        })
      } else {
        that.DetaiData = []
      }
    },
    getUnitGroupList (e) {
      this.queryParam.Condition = 'GroupId'
      this.queryParam.keyword = e
      this.$http
        .post('/Base_BasicData/Base_UnitItems/GetDataList', {
          Search: this.queryParam
        })
        .then((resJson) => {
          if (resJson.Success) {
            this.UnitData = resJson.Data
          }
        })
    },

    // 公司列表
    getCompanyList () {
      this.$http.post('/Base_Manage/Base_Department/GetDepartmentTreeDataList', {}).then((resJson) => {
        if (resJson.Success) {
          this.CompanyIdTreeData = resJson.Data
        }
      })
    },
    // 销售部门列表
    async getDepartmentList (e) {
      await this.$set(this.entity, 'cDepCode', undefined)
      await this.$http.post('/Base_Manage/Base_Department/GetDepartmentList?DeptId=' + e, {}).then((resJson) => {
        if (resJson.Success) {
          this.DepartmentIdTreeData = resJson.Data
        }
      })
    },
    // getDeliveryMethodData () {
    //   this.$http
    //     .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
    //       Condition: 'DicKey',
    //       Keyword: 'DeliveryMethod'
    //     })
    //     .then((res) => {
    //       this.DeliveryMethodData = res.Data.DictionaryDetailsList
    //     })
    // },
    // getPaymentMethodData () {
    //   this.$http
    //     .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
    //       Condition: 'DicKey',
    //       Keyword: 'PaymentMethod'
    //     })
    //     .then((res) => {
    //       this.PaymentMethodData = res.Data.DictionaryDetailsList
    //     })
    // },
    getPaymentTermsData () {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'PaymentTerms'
        })
        .then((res) => {
          this.PaymentTermsData = res.Data.DictionaryDetailsList
        })
    },
    getAccompanyingDocumentsData () {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'AccompanyingDocuments'
        })
        .then((res) => {
          this.AccompanyingDocumentsData = res.Data.DictionaryDetailsList
        })
    },
    getShippingConditionsData () {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'ShippingConditions'
        })
        .then((res) => {
          this.ShippingConditionsData = res.Data.DictionaryDetailsList
        })
    },
    getMaterialClassificationData () {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'MaterialClassification'
        })
        .then((res) => {
          this.MaterialClassificationData = res.Data.DictionaryDetailsList
        })
    },
    getMaterialPropertiesData () {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'InspectMaterialType'
        })
        .then((res) => {
          this.MaterialPropertiesData = res.Data.DictionaryDetailsList
        })
    },
    getUnitGroupData () {
      this.$http.post('/Base_BasicData/Base_UnitGroup/GetDataList', {}).then((resJson) => {
        this.UnitGroupData = resJson.Data
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 获取选中的行
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
    },
    // 跳转最后一页
    toLastPage () {
      const pagination = { ...this.pagination }
      pagination.current = Math.ceil(pagination.total / pagination.pageSize)
      this.pagination = pagination
    },
    // 跳转最后一行
    toLastTableRow () {
      const allDom = document.getElementById('detailsTable').getElementsByClassName('ant-table-body')
      const list = Array.from(allDom)
      list.forEach((item) => {
        item.scrollTop = window.innerHeight + item.scrollTop
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-select-dropdown-menu-item{
    white-space:initial !important;
}
.mainInfo{
  height: 35vh;
}
</style>
